<!-- 入库订单 -->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />


    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="li => selection = li"
      >

    </ex_super_table_page>

    <el-dialog :close-on-click-modal="false" :title="$tt('label_order_audit')" :visible.sync="dialogAudit"
      custom-class="dialog_small">

      <el-form :label-width="$globalCss.formLabelWidth_default" :model="auditForm" :rules="auditRules" ref="AuditForm">
        <el-form-item :label="$tt('text_has_select_order')">
          <ex_super_table v-bind="optionAudit" :data="dialogAuditItems" max-height="300" />
        </el-form-item>
        <el-form-item :label="$tt('label_audit_pass')" class="form_input_default" prop="isAdopt">
          <ex_super_input type="select" v-model="auditForm.isAdopt" enum="YesOrNoEnum" :clearable="false"
            class="widthdiv1" />
        </el-form-item>
        <el-form-item :label="$tt('label_audit_reject_reason')" v-if="auditForm.isAdopt == 'N'" prop="rejectReason">
          <ex_super_input v-model="auditForm.rejectReason" class="widthdiv1" :attrs="{ type: 'textarea' }" autosize
            :placeholder="$tt('label_audit_reject_reason')" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog_footer">
        <el-button @click="dialogAudit = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitAuditOrder">{{ $tt('label_submit') }}</el-button>
      </span>
    </el-dialog>




    <pms-offline-price-config ref="pmsOfflinePriceConfig"
      @afterSubmit="$refs['SuperTablePage'].reload()"></pms-offline-price-config>

    <pms-online-price-config ref="pmsOnlinePriceConfig"
      @afterSubmit="$refs['SuperTablePage'].reload()"></pms-online-price-config>

    <fms-bill-detail-cmp ref="fmsBillDetailCmp"></fms-bill-detail-cmp>

    <report_anomaly ref="report_anomaly" :orderTypeList="['INBOUND']" @afterSubmitSuccess="reload()" />

  </div>
</template>
<script>

import business_function from "@/common/business_function"

import moment from 'moment-mini-ts'

import superTablePageFunction from '@/mixin/super-table-page-function';
import emitOnFunction from '@/mixin/emit-on-function';

import page_table_model_manage from '@/mixin/page_table_model_manage';
let emitKey = 'order=>manage'

import PmsOfflinePriceConfig from '@/component/pms/pms-offline-price-config.vue'

import PmsOnlinePriceConfig from '@/component/pms/pms-online-price-config.vue'

import FmsBillDetailCmp from '@/component/fms/fms-bill-detail-cmp.vue'

import report_anomaly from '@/component/dialog/report_anomaly.vue'

export default {

  title: "title_inbound_order",
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],

  components: {
    PmsOfflinePriceConfig,
    PmsOnlinePriceConfig,
    FmsBillDetailCmp,
    report_anomaly,
  },

  data() {
    return {
      selection: [],
      auditForm: {
        rejectReason: "",
        isAdopt: 'Y',
      },
      auditRules: {
        isAdopt: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' },
        rejectReason: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
      },
      dialogAuditItems: [],
      dialogAudit: false,

      limitDate: null,

      option: {
        search: {
          formDataHandle: (data) => {
            const out = _.cloneDeep(data)
            if (out.daterange.length >= 2&& !out.receivingOrderCodes) {
              out.startCreateTime = out.daterange[0]
              out.endCreateTime = out.daterange[1]
            }
            return out
          },
          default: {
            daterange: [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'months').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]
          },
          model: [
            { label: "label_order_code", key: "receivingOrderCodes", placeholder: 'tip_input_can_comma_separated' },
            { label: "label_customer", key: "customerIds", type: 'common_customer_choose', multiple: true, },
            { label: "label_sku", key: "skuId", type: 'sku_selec_input' },
            // { label: "label_warehouse_name", key: "warehouseName", },

            {
              label: "label_transit_warehouse", key: "transitWarehouseId", type: 'base_warehouse_select', fold: false, isTransit: true,
            },
            { label: "label_order_status", key: "status", type: 'select', enum: 'ReceivingOperationStatusEnum', listHandler: list => list.filter(it => ![ 'WAIT_AUDIT', 'AUDIT_REJECT', 'PURCHASE_INSURANCE_FAIL', 'PICK_UP_LESS', 'RECEIVING_LESS', 'ACCEPTANCE_DIFFERENCES'].includes(it)) },
            {
              label: "label_destination_warehouse", key: "destinationWarehouseId", type: 'base_warehouse_select', fold: false,
              isTransit: false,
            },
            { label: "label_inbound_type", key: "inboundType", type: 'select', enum: 'InboundTypeEnum', fold: true, },
            { label: "label_delivery_type", key: "deliveryType", type: 'select', enum: 'DeliveryTypeEnum', fold: true, },
            { label: 'label_business_type', key: 'bizType', type: 'select', enum: 'BizTypeEnum', fold: true, },

            {
              label: "label_time_range", key: "daterange", type: 'date-picker', fold: false,
              attrs: {
                clearable: false,
                type: 'datetimerange', 'default-time': ['00:00:00', '23:59:59'],
                'popper-class': "no_clear_range_picker",
                'picker-options': {
                  shortcuts: this.$date_range_shortcuts(),
                  onPick: (d) => {
                    this.limitDate = d.minDate
                  },
                  disabledDate: (t) => {
                    if (moment(t).isAfter(moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 999 }))) return true
                    if (this.limitDate != null) {
                      if (moment(t).isAfter(moment(this.limitDate).add(3, 'months')) ||
                        moment(t).isBefore(moment(this.limitDate).subtract(3, 'months'))) {
                        return true
                      }
                    }
                    return false
                  }
                },
              },
              on: {
                blur: () => { this.limitDate = null }
              }
            },
          ],
        },
        actionExtra: [
          {
            label: 'title_new_inbound_oder', attrs: { type: "primary" },
            auth: 'oms_inbound_order_new_edit',
            click: this.creatOrder
          },
          { label: 'label_download_attachment_zip', click: this.downloadAttachmentZip },
        ],
        table: {
          url: "/oms-api/receiving/InboundReceivingRpc/selectPage.json",
          model: this.init_table_model(),
        },
      },
      optionAudit: {
        model: [
          { key: 'receivingOrderCode', label: 'label_order_code' },
          { key: 'customerName', label: 'label_customer_info' },
          {
            type: 'operate', width: 210, operate: [
              {
                label: "label_remove", class: 'button_text_danger',
                click: (row, i) => {
                  this.dialogAuditItems.splice(i, 1)
                  if (_.isEmpty(this.dialogAuditItems)) this.dialogAudit = false
                }
              },]
          }
        ]
      },


    };
  },



  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },
        { key: 'receivingOrderCode', label: 'label_order_code', 'show-overflow-tooltip': true, },
        { key: 'customerName', label: 'label_customer_name', 'width': 100, 'show-overflow-tooltip': true, },
        { key: 'customerCode', label: 'label_customer_code', 'width': 100, 'show-overflow-tooltip': true, },
        { key: 'inboundType', label: 'label_inbound_type', 'width': 120, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$enumShow(v, "InboundTypeEnum") },
        {
          key: 'status', label: 'label_order_status', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "ReceivingOperationStatusEnum")
        },
        {
          key: 'transitWarehouseName', label: 'label_transit_warehouse', 'min-width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$formatNameCode(v, r.transitWarehouseCode)
        },
        { key: 'destinationWarehouseName', label: 'label_destination_warehouse', 'min-width': 120, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$formatNameCode(v, r.destinationWarehouseCode) },
        { key: 'isInsurance', label: 'label_insurance_server', 'width': 120, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum") },
        { key: 'expectBoxQty', label: 'label_expected_box_number', 'width': 100, },
        { key: 'expectSkuQty', label: 'label_expected_sku_number', 'width': 100, },
        {
          label: 'label_business_type', key: 'bizType', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "BizTypeEnum")
        },
        { key: 'gmtCreate', label: 'label_create_order_date', formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'checkoutTime', label: 'label_transfer_checkout_date', formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'overseasPutawayTime', label: 'label_overseas_put_date', formatter: (r, c, v, i) => this.$dateFormat(v) },
        {
          key: 'errorMessage', label: 'label_error_info', width: 180,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!code) return ""
            return (<text_extra_tooltip_operate
              value={code} ellipsis
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        {
          type: 'operate', width: 300, operate: [
            {
              label: "label_audit",
              auth: 'oms_inbound_order_audit',

              if: this.isEditShow,
              disabled: (row) => !['WAIT_AUDIT',].some(e => e == row.status),
              click: (row) => {
                this.dialogAudit = true
                this.dialogAuditItems = [row]
              }
            },
            {
              label: "label_edit",
              auth: 'oms_inbound_order_new_edit',
              if: this.isEditShow,
              disabled: this.isEditDisabled,
              click: (row) => {
                this.editOrder(row)
              }
            },

            // {
            //   label: 'label_delete', type: "confirm-button", buttonClass: "button_text_danger", confirmButtonType: 'danger',
            //   if: this.isEditShow,
            //   disabled: this.isCanDelete,
            //   url: '/oms-api/receiving/InboundReceivingRpc/delete.json', message: 'text_confirm_sure_delete',
            //   params: (v) => { return { receivingId: v.id } }, done: ['reload', 'tip']
            // },

            // ------ FMS -------
            // '报价': '重新报价'
            {
              label: (row) => (row.fmsOrder.versionPriceTag + '' == '0') ? this.$tt('label_quotation') : this.$tt('label_retry_quotation'),
              auth: 'oms_inbound_order_quotation',
              if: (row) => {
                return row.fmsOrder && row.fmsOrder.priceModel == 'OFFLINE'
              },
              click: (row) => {
                this.fmsOrderId = row.fmsOrder.id
                this.$refs['pmsOfflinePriceConfig'].showConfig(row.fmsOrder.id)
              }
            },
            // 重算
            {
              label: 'label_retry_compute',
              auth: 'oms_inbound_order_rerun',
              if: (row) => {
                return row.fmsOrder && row.fmsOrder.priceModel == 'ONLINE' &&
                  (row.fmsOrder.productType == 'FIRST_TRANSPORT' || row.fmsOrder.productType == 'LAST_TRANSPORT')
              },
              click: (row) => {
                this.fmsOrderId = row.fmsOrder.id
                row.fmsOrder = {
                  ...row.fmsOrder, ...{
                    'customerCode': row.customerCode,
                    'customerName': row.customerName
                  }
                }
                this.$refs['pmsOnlinePriceConfig'].showConfig(row.fmsOrder)
              }
            },
            // 结算单
            {
              label: 'label_fms_customer_order_statement',
              if: (row) => {
                return row.fmsOrder && row.fmsOrder.refOrderType != 'TENANT'
              },
              click: (row) => {
                this.$refs['fmsBillDetailCmp'].showDetail(row.fmsOrder)
              }
            },
            // ------ FMS -------

            {
              type: 'more',
              items: [
                { label: 'label_view_detail', click: (row) => this.clickDetail(row) },
                // {
                //   label: 'label_retry',
                //   disabled: (row) => !['GET_TRACK_NUMBER_FAIL', 'PURCHASE_INSURANCE_FAIL'].includes(row.status),
                //   click: (row) => this.clickRetryReceiving(row),
                // },
                {
                  label: 'label_copy_new',
                  auth: "oms_inbound_order_new_edit",
                  click: (row) => this.copyOrder(row),
                },
                { label: 'label_download_attachment', click: row => this.downloadAttachment(row) },
                // { label: 'label_print_barcode', click: row => this.$noFunction() },
                // { label: 'label_order_track', click: row => this.$noFunction() },
                // { label: 'label_view_task_order', click: row => this.$noFunction() },
                // { label: 'label_view_receivable', click: row => this.$noFunction() },
                {
                  label: 'label_report_exception', auth: 'oms_anomaly_report', click: row => {
                    this['$refs']['report_anomaly'].showNew({
                      formDisabled: true,
                      data: {
                        orderType: 'INBOUND',
                        orderNo: row.receivingOrderCode,
                        customerId: row.customerId,
                        customerCode: row.customerCode,
                        customerName: row.customerName,
                      },
                      onlySetData: true,
                    })
                  }
                },
                {
                  label: "label_tms_waybill_check_track",
                  click: (row) => {
                    this.$router.push({ path: '/page/oms/track/track_list', query: { trackNumber: row.receivingOrderCode, } })
                  }
                },
                {
                  label: "label_cancel",
                  click: (row) => this.cancelOrder(row)
                },
              ]
            }
          ],
        },
      ]
    },


    isCanDelete(row) {
      return row.status != 'DRAFT'
    },

    isEditShow(row, i) {
      return row.isWarehouseEdit != 'Y'
    },
    isEditDisabled(row) {
      return row.isUpdatable != 'Y'||row.isPurchaseOrder==='Y'
      let _TRANSIT = row.inboundType == 'TRANSIT'
      let canEdit = false
      if (_TRANSIT) {
        canEdit = ['DRAFT', 'WAIT_AUDIT', 'AUDIT_REJECT', 'TRANSIT_WAIT_INBOUND', 'GET_TRACK_NUMBER_FAIL', 'PURCHASE_INSURANCE_FAIL'].some(e => e == row.status)
      } else {
        canEdit = ['DRAFT', 'WAIT_AUDIT', 'AUDIT_REJECT', 'TRANSIT_TRANSPORT', 'GET_TRACK_NUMBER_FAIL', 'PURCHASE_INSURANCE_FAIL'].some(e => e == row.status)
      }
      return !canEdit
    },
    clickDetail(row) {
      this.$router.push({
        path: '/page/oms/order/inbound/order_detail', query: { receivingId: row.id, }
      })
    },
    copyOrder(row,) {
      const query = { receivingId: row.id, copy: true, edit: true, emitKey }

      this.$router.push({ path: '/page/oms/order/inbound/order_operate', query })
    },
    editOrder(row) {
      this.$router.push({
        path: '/page/oms/order/inbound/order_operate', query: { receivingId: row.id, edit: true, emitKey }
      })
    },
    creatOrder() {
      this.$router.push({ path: '/page/oms/order/inbound/order_operate', query: { emitKey, } })
    },
    clickAuditList() {
      let _list = this.selection
      if (_.isEmpty(_list)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.dialogAuditItems = _.cloneDeep(_list)
      this.dialogAudit = true

    },
    submitAuditOrder() {
      this.$refs['AuditForm'].validate((valid) => {
        if (valid) {
          this.auditOrder()
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      })
    },

    clickRetryReceiving(row) {
      this.$confirm(this.$tt('是否确认重试'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.submitRetryReceiving(row);
      }).catch(() => {
      });
    },
    submitRetryReceiving(row) {
      this.$ajax({
        url: "/oms-api/receiving/InboundReceivingRpc/retryReceiving.json",
        method: 'post',
        loading: true,
        data: {
          receivingId: row.id,
        },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
        },
      })
    },
    downloadAttachmentZip() {
      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: this.$refs.SuperTablePage.getSearchFormData(),
        model: this.option.search.model,
        selection: this.selection,
        callback: (selection, data) => {
          let params = {}
          if (!_.isEmpty(selection)) {
            params = {
              receivingOrderCodes: selection.map(it => it.receivingOrderCode)
            }
          } else {
            params = data
          }
          this.$downloadFile({
            window: true,
            url: "/oms-api/receiving/InboundReceivingRpc/batchDownloadAttached.json",
            data: params,
          })
        }
      })

    },
    downloadAttachment(row) {
      if (row.attachment_list) {
        this.showOrderAttachmentBox(row)
        return
      }
      this.$ajax({
        url: this.$url['oms/downloadInboundAttachment'],
        method: 'post',
        loading: true,
        data: {
          receivingId: row.id,
        },
        success: (res) => {
          if (res.data && res.data.rows) {
            row.attachment_list = res.data.rows
            this.showOrderAttachmentBox(row)
          }
        },
      })
    },
    showOrderAttachmentBox(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: this.$tt('label_attachment_download'),
        message: h('div', null,
          row.attachment_list.map(it => {
            return h('div', { class: 'mg_v1' }, [
              h('a', {
                class: 'a_file_link',
                attrs: {
                  href: this.$ex_default_download_url + it.filePath,
                  target: '_blank',
                  download: it.fileName,
                }
              }, [h('i', { class: 'el-icon-download el-icon--left' }), it.fileName])
            ])
          })),
        // showCancelButton: true,
        showConfirmButton: false,
      }).then(action => {

      });
    },
    auditOrder() {
      let data = _.clone(this.auditForm)
      data.receivingIdList = this.dialogAuditItems.map(it => it.id)
      let isNeedReloadTransfer = this.dialogAuditItems.some(it => it.inboundType == 'TRANSIT')
      let isNeedReloadDirect = this.dialogAuditItems.some(it => it.inboundType == 'DIRECT')
      this.$ajax({
        url: "/oms-api/receiving/InboundReceivingRpc/audit.json",
        method: 'post', type: 'json',
        loading: this.$tt('tip_submiting'),
        data,
        success: (res) => {
          this.dialogAudit = false
          this.reload()
          this.$message.success(this.$tt('tip_submit_success'))
          if (isNeedReloadTransfer) this.$emitPage('transfer=>receiving_list', 'reload')
          if (isNeedReloadDirect) this.$emitPage('standard>inbound_manage', 'reload')
        }
      })
    },
    cancelOrder(row) {
      this.$confirm(this.$tt('tip_confirm_cancel_select_order_any_cancel_no_replay', { any: row.receivingOrderCode }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/inboundOrder/cancelOrder'],
          method: 'post',
          loading: true,
          data: {
            id: row.id
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
  }
};

</script>
<style></style>
